<style lang="scss" scoped>
    .page {
        background: white;
        padding: 25px;

        ::v-deep .el-dialog {
            width: 80%;
            max-width: 500px;

            .el-dialog__body {
                padding: 10px 20px;
            }
        }
    }
</style>
<template>
    <div class="page">
        <el-row class="m-b-0">
            <el-button type="primary" size="medium" icon="el-icon-plus" @click="addUser">添加用户</el-button>
        </el-row>
        <el-table
                v-loading="loading"
                :data="tableData.items"
                style="width: 100%;margin-bottom: 20px;"
                row-key="id">
            <el-table-column prop="id" label="Id" width="60"></el-table-column>
            <el-table-column prop="userName" label="用户名"></el-table-column>
            <el-table-column prop="name" label="姓名/昵称"></el-table-column>
            <!--<el-table-column prop="emailAddress" label="邮箱"></el-table-column>-->
            <el-table-column label="状态">
                <template slot-scope="scope">
                    <el-tag type="success" v-if="scope.row.isActive">可用</el-tag>
                    <el-tag type="danger" v-else>禁用</el-tag>
                </template>
            </el-table-column>
            <!-- <el-table-column
                prop="lastLoginTime"
                label="最后登录时间">
            </el-table-column> -->
            <el-table-column
                    prop="creationTime"
                    label="创建时间">
            </el-table-column>
            <el-table-column label="操作" width="250">
                <template slot-scope="scope">
                    <el-button
                            size="mini"
                            @click="handleEdit(scope.$index, scope.row)">编辑
                    </el-button>
                    <el-button
                            size="mini"
                            @click="resetPassword(scope.row)">重置密码
                    </el-button>
                    <el-button
                            size="mini"
                            type="danger"
                            @click="_delete(scope.row.id)">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
                @size-change="(_size)=>{ filter.size = _size; getData()}"
                @current-change="(_page)=>{ filter.page = _page; getData()}"
                :current-page="filter.page"
                :page-sizes="defaultPageSize"
                :page-size="filter.size"
                layout="total, sizes, prev, pager, next, jumper"
                background
                :total="tableData.totalCount" style="margin-top: 20px;">
        </el-pagination>

        <el-dialog :title="model.id===0?'添加用户':'修改用户'" :visible.sync="dialogFormVisible"
                   :close-on-click-modal="false" @closed="editLoading=false">

            <el-form :model="model" ref="editForm" :rules="rules" label-width="100px">
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="model.name" placeholder="" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="用户名" prop="userName">
                    <el-input v-model="model.userName" placeholder="中文、字母、数字皆可" autocomplete="off"></el-input>
                </el-form-item>
                <!--修改数据时不显示密码-->
                <el-form-item label="密码" prop="password" v-show="model.id === 0">
                    <el-input v-model="model.password" placeholder="请输入6-32位密码" autocomplete="off"></el-input>
                </el-form-item>
                <!--<el-form-item label="邮箱" prop="emailAddress">
                    <el-input v-model="model.emailAddress" placeholder="选填" autocomplete="off"></el-input>
                </el-form-item>-->
                <el-form-item label="是否可用">
                    <el-switch v-model="model.isActive"></el-switch>
                </el-form-item>
                <el-form-item label="角色" prop="roleNames">
                    <el-checkbox-group v-model="model.roleNames">
                        <el-checkbox :label="role.code" :key="role.code" v-for="role in roles">
                            {{role.name}}
                        </el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm" :loading="editLoading">确 定
                </el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
    let pagerHeader = {
        title: '用户管理',
        desc: '添加、修改管理用户，设置用户角色以便控制其管理权限。',
        breadcrumb: ['系统', '用户管理']
    }
    let modelStr = JSON.stringify({
        id: 0,
        userName: null,
        name: null,
        surname: 'Admin',
        emailAddress: null,
        isActive: true,
        roleNames: [
            //'string'
        ],
        password: null
    })
    export default {
        name: 'system_users',
        data() {
            return {
                dialogFormVisible: false,
                filter: {
                    page: 1,
                    size: 15,
                },
                model: JSON.parse(modelStr),
                rules: {
                    userName: [
                        {required: true, message: '请输入用户名', trigger: 'blur'},
                    ],
                    name: [
                        {required: true, message: '请输入姓名或昵称', trigger: 'blur'},
                    ],
                    roleNames: [
                        {required: true, message: '请选择角色', trigger: 'change'},
                        /*{
                            validator: (rule, value, callback) => {
                                console.log(value)
                                if (!value || value.length === 0) {
                                    callback(new Error('请选择角色'))
                                } else {
                                    callback()
                                }
                            }, trigger: 'change'
                        },*/
                    ],
                    password: [
                        {
                            validator: (rule, value, callback) => {
                                if (this.model.id === 0 && /^.{6,32}$/.test(value) === false) {
                                    callback(new Error('请输入密码（6-32位字）'))
                                } else {
                                    callback()
                                }
                            }, trigger: 'change'
                        },
                    ]
                },
                loading: false,
                editLoading: false,
                roles: [],
                tableData: {
                    items: [],
                    totalCount: 0
                },
            }
        },
        activated() {
            this.setPageHead(pagerHeader)
            this.getRoles()
            this.getData()
        },
        created() {
            this.setPageHead(pagerHeader)
            this.getRoles()
            this.getData()
        },
        methods: {
            getData() {
                this.loading = true
                /*let params = {
                    "skipCount": (this.filter.page - 1) * this.filter.size,
                    "maxResultCount": this.filter.size
                }*/
                this.loading = true
                this.$apis.users.getUsers(this.filter).then(r => {
                    this.loading = false;
                    if (r.success)
                        this.tableData = r.result;
                    else
                        this.$msg.alert.error(r.error.message)
                }).catch(e => {
                    this.loading = false;
                })
            },
            getRoles() {
                this.$apis.users.getRoles({page: 1, size: 100}).then(r => {
                    this.loading = false;
                    if (r.success)
                        this.roles = r.result.items;
                    else
                        this.$msg.alert.error(r.error.message)
                }).catch(e => {
                    this.loading = false;
                })
            },
            addUser() {
                if (this.model.id > 0) {
                    this.model = JSON.parse(modelStr)
                    this.$nextTick(() => {
                        this.$refs.editForm.clearValidate();
                    })
                }
                this.dialogFormVisible = true
            },
            handleEdit(index, row) {
                this.loading = true;
                this.$apis.users.getUserEditDto(row.id).then(r => {
                    this.loading = false;
                    if (r.success) {
                        console.log(r.result)
                        this.model = {
                            id: r.result.id,
                            userName: r.result.userName,
                            name: r.result.name,
                            surname: r.result.surname,
                            emailAddress: r.result.emailAddress,
                            isActive: r.result.isActive,
                            roleNames: r.result.roles,
                        }
                        this.dialogFormVisible = true;
                        this.$nextTick(() => {
                            this.$refs.editForm.clearValidate();
                        })
                    } else
                        this.$msg.alert.error(r.error.message)
                }).catch(e => {
                    this.loading = false;
                })
            },
            resetPassword(user) {
                this.$prompt('请输入密码', '', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    closeOnClickModal: false,
                    inputPlaceholder: '密码只能由6-20位字母、数字、下划线组成',
                    inputValue: '',
                    inputPattern: /^\w{6,20}$/,
                    inputErrorMessage: '密码只能由6-20位字母、数字、下划线组成',
                }).then(({value}) => {
                    this.$apis.users.resetPassword({id: user.id, password: value}).then(r => {
                        if (r.success) {
                            this.$msg.notify.success('密码修改成功')
                        } else {
                            this.$msg.alert.error(r.error.message)
                        }
                    }).catch(e => { })
                }).catch(() => { })
            },
            _delete(id) {
                this.$confirm('此操作将删除数据, 是否继续?', '', {
                    confirmButtonText: '是',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.loading = true
                    this.$apis.users.delete(id).then(r => {
                        this.loading = false
                        if (r.success) {
                            this.getData()
                            this.$notify({title: '删除成功', message: '', type: 'success'})
                        } else {
                            this.$msg.alert.error(r.error.message)
                        }
                    }).catch(e => {
                        this.loading = false
                    })
                }).catch(e => {
                    this.loading = false
                })
            },
            resetForm() {
                this.model = JSON.parse(modelStr)
                this.$nextTick(() => {
                    this.$refs.editForm.clearValidate();
                })
            },
            submitForm() {
                this.$refs.editForm.validate((valid) => {
                    if (valid) {
                        if (this.model.id === 0) {
                            this.model.emailAddress = this.randomString(20) + '@test.com';
                        }
                        this.editLoading = true;
                        this.$apis.users.saveUser(this.model).then(r => {
                            this.editLoading = false;
                            this.$msg.notify.success('成功', this.model.id === 0 ? '用户添加成功' : '用户修改成功')
                            if (this.model.id > 0) {
                                this.dialogFormVisible = false;
                            }
                            this.resetForm();
                        }).catch(e => {
                            this.editLoading = false;
                        })
                    }
                })
            },
        }
    }
</script>
